package com.server.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import com.server.servlet.Servlet;
import com.server.servlet.ServletContext;

public class HttpResponse {
	
	private OutputStream out;
	private Socket socket;
	private File file;
	private String type;
	private String reqUri;
	private HttpRequest request;
	
	public HttpResponse(Socket socket, String reqUri, HttpRequest request){
		this.socket = socket;
		try {
			this.out = socket.getOutputStream();
			this.reqUri = reqUri;
			this.request = request;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void flush(){
		HttpResponse response = this;
		if(ServletContext.servletIsExit(reqUri)){
			Servlet servlet = ServletContext.getServlet(reqUri);
			servlet.service(request, response);
			flush();
		}else{
			type = reqUri.split("\\.")[1];
			
			String path = "./webapps" + reqUri;
			
			file = new File(path);
			//如果不存在则传404
			if(!file.exists()){
				file = new File("./webapps/root/web404.html");
			}
			sendResLine();
			sendResHead();
			sendFile();
			
			
		}
		
	}
	
	private void sendResLine(){
		try {
			String resLine = "HTTP/1.1 200 OK";
			byte[] line = resLine.getBytes("ISO8859-1");
			out.write(line);
			out.write(13);
			out.write(10);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	
	private void sendResHead(){
		try {
			String resLine = "Content-Type:" + HttpContext.getType(type);
			byte[] line = resLine.getBytes("ISO8859-1");
			out.write(line);
			out.write(13);
			out.write(10);
			
			resLine = "Content-Length:" + file.length();
			line = resLine.getBytes("ISO8859-1");
			out.write(line);
			out.write(13);
			out.write(10);
			out.write(13);
			out.write(10);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	
	
	private void sendFile(){
		try {
			FileInputStream fis = new FileInputStream(file);
			byte[] data = new byte[10 * 1024];
			while(fis.read(data) != -1){
				out.write(data);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setReqUri(String reqUri) {
		this.reqUri = reqUri;
	}
	
}
